package com.dingwen.auause.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;

import javax.sql.DataSource;

/**
 * 配置认证服务器
 *
 * @author dingwen
 * 2021.05.12 14:37
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private static final String CLIENT_ID = "web_dev";
    private static final String SECRET = "dingwen_web";
    private static final String AUTHORIZED_GRANT_TYPES = "authorization_code";
    private static final String SCOPES = "write";
    private static final String REDIRECT_URIS = "http:///www.baidu.com";
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final DataSource dataSource;

    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;

    @Autowired
    AuthorizationServerConfiguration(BCryptPasswordEncoder bCryptPasswordEncoder,
                                     DataSource dataSource,
                                     AuthenticationManager authenticationManager,
                                     UserDetailsService userDetailsService
    ) {
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.dataSource = dataSource;
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
    }

    /*
     * 配置 TokenStore
     * @return TokenStore
     */
    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    /*
     * jdbc 客户端服务
     * @return ClientDetailsService
     */
    @Bean
    public ClientDetailsService jdbcClientDetails() {// 必须是这个方法名称
        return new JdbcClientDetailsService(dataSource);
    }

    /*
     * 配置客户端
     * @param clients
     *
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 内存模式
        /*clients //配置客户端
                .inMemory() // 试用内存设置
                .withClient(CLIENT_ID) //客户端标识
                .secret(bCryptPasswordEncoder.encode(SECRET)) //客户端安全码
                .authorizedGrantTypes(AUTHORIZED_GRANT_TYPES)//授权类型
                .scopes(SCOPES)//授权范围
                .redirectUris(REDIRECT_URIS);// 注册回调地址

         */

        // 数据库模式
        clients.withClientDetails(jdbcClientDetails());


    }

    // 设置令牌
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .tokenServices(defaultTokenServices())
                .userDetailsService(userDetailsService);
    }

    @Bean
    public AuthorizationServerTokenServices defaultTokenServices() throws Exception {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setAuthenticationManager(this.authenticationManager);
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setClientDetailsService(jdbcClientDetails());

        // access token有效期2个小时
        defaultTokenServices.setAccessTokenValiditySeconds(60 * 60 * 2);
        // refresh token有效期30天
        defaultTokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 30);
        // 支持使用refresh token刷新access token
        defaultTokenServices.setSupportRefreshToken(true);
        // 允许重复使用refresh token
        defaultTokenServices.setReuseRefreshToken(true);
        return defaultTokenServices;
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll()");
        security.checkTokenAccess("isAuthenticated()");
        // 允许使用客户端id和客户端secret获取token
        security.allowFormAuthenticationForClients();
    }
}



